package me.luraframework.commons.utils;

import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.type.CollectionType;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class JsonUtils {

    private static Gson gson = new GsonBuilder().create();
    private static ObjectMapper objectMapper = new ObjectMapper();

    public static String toStr(Object obj) {
       return gson.toJson(obj);
    }

    public static <T> T toObj(String jsonStr, Class<T> clazz) {
        return gson.fromJson(jsonStr, clazz);
    }

    public static <T> List<T> toList(String jsonStr, TypeReference<T> reference) {
        try {
            return objectMapper.readValue(jsonStr, reference);
        } catch (IOException e) {
            return null;
        }
    }

    public static <T> T toObj(String jsonStr, TypeReference<T> reference) {
        try {
            return objectMapper.readValue(jsonStr, reference);
        } catch (IOException e) {
            return null;
        }
    }

    public static <T> List<T> toList(String jsonStr, Class<T> clazz) {
        JavaType javaType = objectMapper.getTypeFactory().constructCollectionType(List.class, clazz);
        try {
            return objectMapper.readValue(jsonStr, javaType);
        } catch (IOException e) {
            return null;
        }
    }
}
